package com.itrip.controller;

import com.itrip.dto.ResponseDTO;
import com.itrip.mail.SendMail;
import com.itrip.pojo.ItripUser;
import com.itrip.service.UserService;
import com.itrip.utils.MD5;
import com.itrip.utils.PhoneMessage;
import com.itrip.vo.user.LoginVo;
import com.itrip.vo.user.RegistVo;
import io.swagger.annotations.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Api(tags = "登陆，注销接口")
@ApiResponses({
        @ApiResponse(code=200,message = "成功登陆",response = ResponseDTO.class)
})
@RestController
public class LoginController {
    @Resource
    private UserService userService;

    @Resource
    RedisTemplate redisTemplate;


    @GetMapping("/getPowerCode")
    @ApiOperation("通过邮箱获取授权码")
    public Object getPowerCode(){
        //生产验证码
        int powerCode=(int)((Math.random()*9+1)*1000000);

        //发送邮箱的地址
        String mails="3193087037@qq.com";
        //将获取到的验证码存入reids,并将它和邮箱绑定在验证完之后删除
        redisTemplate.opsForValue().set(mails,Integer.toString(powerCode),10,TimeUnit.MINUTES);
        //调用发送信息的函数
        SendMail.send(Integer.toString(powerCode),mails);

        return new  ResponseDTO(100,"获取授权码成功",Integer.toString(powerCode));
    }



    @GetMapping("/getPowerCodeByPhone")
    @ApiOperation("通过手机获取授权码")
    public Object getPowerCodeByPhone(){
        //生产验证码
        int powerCode=(int)((Math.random()*9+1)*100000);

        //发送邮箱的地址
        String phone="15696477860";
        //将获取到的验证码存入reids,并将它和邮箱绑定在验证完之后删除
        redisTemplate.opsForValue().set(phone,Integer.toString(powerCode),10,TimeUnit.MINUTES);
        //调用发送信息的函数
        PhoneMessage.sendPhoneMessage(phone,Integer.toString(powerCode));

        return new  ResponseDTO(100,"获取授权码成功",Integer.toString(powerCode));
    }




    @ApiOperation("用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode",value = "用户编码",dataType = "String"),
            @ApiImplicitParam(name = "userPassword",value = "用户密码",dataType = "String"),
            @ApiImplicitParam(name = "powerCode",value = "用户授权码",dataType = "String")
    })
    @PostMapping(value = "/userRegist",params = {"userCode","userPassword","powerCode"})
    public ResponseDTO userRegist(RegistVo registVo){
        //获取前端传递授权码
        String powerCode = registVo.getPowerCode();
        //根据邮箱获取这个授权码
        String powerCodeT = redisTemplate.opsForValue().get(registVo.getUserCode()).toString();
        //生成ResponseDTO对象
        ResponseDTO responseDTO=null;
        if(powerCodeT!=null&&powerCodeT.equals(powerCode)){
            /*开始存储对象*/
            /*//判断这个邮箱是否已经注册,点击注册这个按钮时候才进行判断.其他：？？？？？前端失去焦点时候返回错误*/
            //获取userCode为邮箱或者电话号码
             String userCode=registVo.getUserCode();
            //判断这个邮箱在数据库中的个数
            Integer userCount=userService.getCountOfUser(userCode);
            if(userCount!=0){
                //直接返回失败对象
                return new ResponseDTO(101,"用户编码已存在",null);
            }
            //成功后删除这个用户的授权码
            redisTemplate.delete(registVo.getUserCode());
            //初始化用户对象
            ItripUser itripUser=new ItripUser();
            itripUser.setUserCode(registVo.getUserCode());
            itripUser.setUserPassword(MD5.md5(registVo.getUserPassword()));
            itripUser.setUserType(0);
            itripUser.setUserName(registVo.getUserCode());
            itripUser.setCreationDate(new Date());
            //将这个对象存储到数据库
            Integer count = userService.userRegist(itripUser);
            if(count!=0){
                responseDTO=new ResponseDTO(100,"用户存储成功","123456");
            }else {
                responseDTO=new ResponseDTO(101,"用户存储失败","null");
            }
        }else{
            //授权码错误或为空
            responseDTO=new ResponseDTO(101,"授权码错误",null);
        }

        return responseDTO;
    }




    @ApiOperation("获取用户信息接口")
    @ApiImplicitParam(name="token",value="token令牌",dataType = "String",paramType = "header")
    @GetMapping("/view/getUser")
    public Object getUserInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        Object user = redisTemplate.opsForValue().get(token);
        return user;
    }






    @ApiOperation("用户注销接口")
    //所需要的参数
    @ApiImplicitParam(name = "token",value ="token令牌",dataType = "String",paramType = "header")
    @GetMapping("/view/loginout")
    public ResponseDTO loginout(HttpServletRequest request){
        String token=request.getHeader("token");
        redisTemplate.delete("token");
        return new ResponseDTO(100,"退出成功",null);
    }


    @ApiOperation("用户登陆接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode",value = "用户编码",dataType = "String",example = "1044732267@qq.com"),
            @ApiImplicitParam(name = "userPassword",value = "用户",dataType = "String",example = "123456")

    })
    @PostMapping(value = "/login",params = {"userCode","userPassword"})
    public ResponseDTO loginCheck(LoginVo loginVo){
        //int c=1/0;
        String password = MD5.md5(loginVo.getUserPassword());
        loginVo.setUserPassword(password);
        ItripUser itripUser= userService.loginCheck(loginVo);

        if(itripUser!=null){
            //用UUID生成token
            String uuid = UUID.randomUUID().toString();
            //将token存入redis
            redisTemplate.opsForValue().set(uuid,itripUser,60*5, TimeUnit.MINUTES);
            return new ResponseDTO(100,"请求成功",uuid);
        }
        return new ResponseDTO(101,"请求失败",null);
    }
}
//http://127.0.0.1:9090/show/login?userCode=1044732267@qq.com&userPassword=e10adc3949ba59abbe56e057f20f883e